// pages/wine/wine.js
const app = getApp()
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    limit: 30,
    page: 1,
    total_page: 0,
    wineList: [], //列表
    hasMore: true,
    wineDome: true,  //酒柜弹窗控制
    numbers: 1,
    buyGoods: [], //购买商品信息 
    fadeInText:true,  //蒙层控制
    fadeInTextHops:true,  //酒花弹窗控制
    fadeInMarryText: true,  //合成成功弹窗控制
    lastTime:0,
    listType:1,
    codeCol: false,
    imagesCol:true, //引导页图片显示控制
    guideFocus:true, //关注公众号引导
    focusSuccessful:false, //关注组件加载状态
    focusComponent:false, //关注组件是否显示
    nav_height:0,
    container_height:70,
    doNumber_height:0,
    orderNum: 0,
    giftCardNum: 0,
    countNum:0,
    show_order_gift: false,
  },
  toTop: function () {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 10
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {
    this.toTop();
    if (app.globalData.sku_code){
      var sku_code = app.globalData.sku_code
    }else{
      var sku_code=''
    }
    // console.log(sku_code);
    if (app.globalData.winType){
      this.setData({
        listType: app.globalData.winType
      })
    }

    this.userStatus();

    wx.hideShareMenu() // 隐藏分享按钮
    this.setData({
      first_flag: (app.globalData.accountInfo.first_flag == 1) ? true : false,  //是否第一次登录小程序
      imagesCol: true,
      wineList: [],
      page: 1,
      total_page: 0,
      wineDome: true,
      sku_code:sku_code,
      wine_guide: app.globalData.base_url + 'images/wine_guide.png? ' + Math.random() / 9999,
      wine_blank: app.globalData.base_url + 'images/wine_blank.png? ' + Math.random() / 9999,
      focusComponent: false, //关注组件是否显示
    })
    this.wineList();
    this.hopsList();
    this.subscribe();
  },

//获取关注公众号状态
  subscribe: function () {
    var that = this;
    var params = new Object()
    params.uid = wx.getStorageSync('accountInfo').uid
    api.POST({
      params: params,
      url: app.globalData.base_url + 'askWine/subscribe',
      success: function (res) {
        // console.log(res.data);
        if (util.isEmpty(res.data.code)) {
          that.setData({
            subscribe: res.data.data.subscribe
          })
          setTimeout(function(){
            that.getHeightInfo();
          },300)
        } else {
          util.showError(res.data.message);
        }
      },
      fail() {
        util.showError("网络错误");
      }
    })
  },

   //设置高度
   getHeightInfo: function () {
      var that = this;
      var nav_height = 0;
      var doNumber_height = 0;
      var container_height = 35;

      if (that.data.subscribe == 0) {   //未关注
         if (that.data.focusComponent) {  //显示关注组件
            nav_height += 84;
            container_height += 84;
            if (that.data.orderNum > 0 && that.data.giftCardNum > 0) {
               //显示订单数量和礼品卡数量
               nav_height += 84;
               container_height += 84;
               doNumber_height = 60;
            } else if (that.data.orderNum > 0 || that.data.giftCardNum > 0) {
               //显示订单数量或礼品卡数量
               nav_height += 64;
               container_height += 64;
               doNumber_height = 40;
            }
         } else {
            nav_height += 83;
            container_height += 83;
            if (that.data.orderNum > 0 && that.data.giftCardNum > 0) {
               //显示订单数量和礼品卡数量
               nav_height += 60;
               container_height += 60;
               doNumber_height = 60;
            } else if (that.data.orderNum > 0 || that.data.giftCardNum > 0) {
               //显示订单数量或礼品卡数量
               nav_height += 40;
               container_height += 40;
               doNumber_height = 40;
            }
         }
      } else {
         if (that.data.orderNum > 0 && that.data.giftCardNum > 0) {
            //显示订单数量和礼品卡数量
            nav_height += 80;
            container_height += 80;
            doNumber_height = 60;
         } else if (that.data.orderNum > 0 || that.data.giftCardNum > 0) {
            //显示订单数量或礼品卡数量
            nav_height += 60;
            container_height += 60;
            doNumber_height = 40;
         }
      }

      that.setData({
         nav_height: nav_height,
         container_height: container_height,
         doNumber_height: doNumber_height,
      })
   },

  winTypeSel:function(e){
    this.toTop();
    this.outSelect();
    this.outSelectHops();
    this.setData({
      listType: e.currentTarget.dataset.type,
      sku_code:""
    })
    app.globalData.winType = e.currentTarget.dataset.type
  },
  winTypeSelTo: function (e) {
    this.outSelect();
    this.outSelectHops();
    this.setData({
      listType: e.currentTarget.dataset.type,
      sku_code: e.currentTarget.dataset.code
    })
    app.globalData.winType = e.currentTarget.dataset.type
  },

  // 淡入
  fadeIn:function(){
    var that = this;
    var fadeIn = wx.createAnimation({
      duration: 500
    })
    that.setData({
      fadeInText: false
    })
    fadeIn.opacity(1).step();
    that.setData({
      animationData: fadeIn.export()
    })
  },
  // 淡出
  fadeOut:function(){
    var that =this;
    var fadeOut = wx.createAnimation({
      duration: 500
    })
    fadeOut.opacity(0).step();
    that.setData({
      animationData: fadeOut.export()
    })
    let timer = setTimeout(function () {
      that.setData({
        fadeInText: true
      })
      clearTimeout(timer);
    }, 500)
  },
  // 飞入
  flyInto:function(){
    var that = this;
    var flyInto = wx.createAnimation({
      duration: 300
    })
    flyInto.bottom("20rpx").step();
    that.setData({
      flyIntoData: flyInto.export()
    })
  },
  // 飞出
  flyOut:function(){
    var that = this;
    var flyOut = wx.createAnimation({
      duration: 300
    })
    flyOut.bottom('-400rpx').step();
    that.setData({
      flyIntoData: flyOut.export()
    })
  },

  // 酒花淡入
  fadeInHops: function () {
    var that = this;
    var fadeInHops = wx.createAnimation({
      duration: 500
    })
    that.setData({
      fadeInTextHops: false
    })
    fadeInHops.opacity(1).step();
    that.setData({
      animationDataHops: fadeInHops.export()
    })
  },
  // 酒花淡出
  fadeOutHops: function () {
    var that = this;
    var fadeOutHops = wx.createAnimation({
      duration: 500
    })
    fadeOutHops.opacity(0).step();
    that.setData({
      animationDataHops: fadeOutHops.export()
    })
    let timer = setTimeout(function () {
      that.setData({
        fadeInTextHops: true
      })
      clearTimeout(timer);
    }, 500)
  },
  // 酒花飞入
  flyIntoHops: function () {
    var that = this;
    var flyIntoHops = wx.createAnimation({
      duration: 300
    })
    flyIntoHops.bottom("20rpx").step();
    that.setData({
      flyIntoDataHops: flyIntoHops.export()
    })
  },
  // 酒花飞出
  flyOutHops: function () {
    var that = this;
    var flyOutHops = wx.createAnimation({
      duration: 300
    })
    flyOutHops.bottom('-400rpx').step();
    that.setData({
      flyIntoDataHops: flyOutHops.export()
    })
  },

  // 合成淡入
  fadeInMarry: function () {
    var that = this;
    var fadeInMarry = wx.createAnimation({
      duration: 500
    })
    that.setData({
      fadeInMarryText: false
    })
    fadeInMarry.opacity(1).step();
    that.setData({
      animationData: fadeInMarry.export()
    })
  },
  // 合成淡出
  fadeOutMarry: function () {
    var that = this;
    var fadeOutMarry = wx.createAnimation({
      duration: 500
    })
    fadeOutMarry.opacity(0).step();
    that.setData({
      animationData: fadeOutMarry.export()
    })
    let timer = setTimeout(function () {
      that.setData({
        fadeInMarryText: true
      })
      clearTimeout(timer);
    }, 500)
  },


  // 显示酒花操作按钮
  intoSelectHops: function (e) {
    var that = this;
    this.setData({
      goodsInfoHops: e.currentTarget.dataset.goodsInfo
    })
    var id = this.data.goodsInfoHops.id;
    api.POST({
      params: { id: id },
      url: app.globalData.base_url + 'hops/createLog',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          // console.log()
          that.setData({
            linkCode: res.data.data.result.linkCode
          })
          that.fadeInHops();
          that.flyIntoHops();
        } else {
          util.showError(res.data.code);
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");
      }
    })

  },
//关闭引导页
  guidePageCol:function(){

    if (!this.data.imagesCol){
      this.setData({
        first_flag: false
      })
      app.globalData.accountInfo.first_flag=2;
    }

  },

  //切换引导页图片
  guideImagesCol:function(){
    this.setData({
      imagesCol:false
    })
  },

  // 隐藏操作按钮
  outSelectHops: function () {
    this.flyOutHops();
    this.fadeOutHops();
    this.fadeOutMarry();
  },

// 显示酒柜操作按钮
intoSelect:function(e){
  var that = this
//   console.log(e.currentTarget.dataset.goodsInfo)
  this.setData({
    goodsInfo:e.currentTarget.dataset.goodsInfo
  })
  that.fadeIn();
  that.flyInto();
},
// 隐藏酒花操作按钮
outSelect:function(){
  this.flyOut();
  this.fadeOut();
},
   onHide:function(){
    app.globalData.sku_code='';
    this.setData({
       show_order_gift:false,
       nav_height:0,
      container_height:35,
      doNumber_height:0,
      orderNum: 0,
      giftCardNum: 0
    })
   //  console.log("2222");
    this.outSelect();
  },

  //页面下拉刷新
  onPullDownRefresh: function () {
    var that = this;
    setTimeout(function () {
      that.resetData()
    }, 1000)
  },
  //刷新页面
  resetData: function () {
    var that = this
    that.setData({
      page: 1,
      // hasMore: true
    });
    that.wineList();
  },

  //页面上拉触底
  onReachBottom: function (e) {
    this.loadMore();
  },

  //加载更多
  loadMore: function () {
    // console.log("到底啦！")
    if (this.data.page >= this.data.total_page) {
      return;
    }
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      page: this.data.page + 1
    });
    this.wineList();
  },

  // 酒花列表获取
  hopsList:function(){
    var that = this;
    api.POST({
      params: {
      },
      url: app.globalData.base_url + 'hops/mylist',
      success: function (res) {
        wx.hideLoading()
        if (util.isEmpty(res.data.code)) {
          var hopsList = res.data.data.result
          hopsList.forEach(function(item){
            // console.log(item)
            item.percent = ((item.num / item.use_num)*100).toFixed(0)
          })
          // console.log(hopsList)
          var data = res.data.data.result
          that.split_array(data,3,"hops")
          // that.setData({
          //   hopsList: res.data.data.result
          // });

        } else {
          util.showError(res.data.code);
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");
      }
    })
  },

  //酒柜列表
  wineList: function () {
    var that = this;
    api.POST({
      params: {
        page: that.data.page,
        limit: that.data.limit
      },
      url: app.globalData.base_url + 'winecabinet/index',
      success: function (res) {
        wx.hideLoading()
        if (util.isEmpty(res.data.code)) {
          var paging = res.data.data.paging;
          var totalPage = paging.total_page;
          var currentPage = paging.page;
          var count = paging.count;
          var resultList = res.data.data.list;
          if (currentPage == 1) {
            var itemData = resultList;
          } else {
            var itemData = that.data.wineList.concat(resultList);
          }
          that.split_array(itemData,3,"winBox");
          that.setData({
            hasMore: (currentPage >= totalPage) ? false : true,
            total_page: totalPage,
            wineList: itemData,
             pickupOrderNum: res.data.data.pickupOrderNum,  
             pickupProductNum: res.data.data.pickupProductNum,
             giftCardNum: res.data.data.giftCardNum,
             giftProductNum: res.data.data.giftProductNum,
             deliveryOrderNum: res.data.data.deliveryOrderNum,
             deliveryProductNum: res.data.data.deliveryProductNum,
             orderNum: res.data.data.orderNum
          });
          setTimeout(function () {
            that.getHeightInfo();
          }, 300)
        } else {
          util.showError(res.data.code);
        }
        wx.stopPullDownRefresh();
      },
      fail: function (fail) {
        wx.hideLoading()
        util.showError("网络错误，请检查网络");
      }
    })
  },

  // 已购买商品详情
  goodsInfo: function (e) {
    var goodsInfo =this.data.goodsInfo;
    wx.navigateTo({
      url: '/wine/pages/wineSelfGet/wineSelfGet?sku_code=' + goodsInfo.sku_code
    })
  },
// 
  //立即购买
  buyNow: function (e) {
    // console.log("立即购买")
    var that = this;
    var goodsInfo = that.data.goodsInfo;
    var sku_code = goodsInfo.sku_code;
    var curTime = e.timeStamp;
    var lastTime = this.data.lastTime;
    this.setData({
      lastTime: curTime
    })
    if (lastTime > 0) {
      if (curTime - lastTime < 500) {
        return false;
      }
    }
    wx.navigateTo({
      url: '/index/pages/productDetails/productDetails?sku_code=' + sku_code
    })
  },
  toStores:function(){
    wx.navigateTo({
      url: '/map/pages/shopAddress/shopAddress?sku_code=' + this.data.goodsInfo.sku_code
    })
  },
  goToHops:function(){
    wx.navigateTo({
      url: '/play/pages/hops/hops'
    })
  },
  closeBuy: function () {
    this.setData({
      wineDome: true
    })
  },

  addNum: function () {
    var num = this.data.numbers;
    num++;
    this.setData({
      numbers: num
    })
  },
  minusNum: function () {
    var num = this.data.numbers;
    if (num > 1) {
      num--;
      this.setData({
        numbers: num
      })
    }
  },

  // 支付订单
  payOrder: function () {
    var that = this;
    var buyGoods = that.data.buyGoods;
    var params = new Object()
    params.record = [];
    var list = [];
    var box = {};
    box.sku_code = buyGoods.sku_code
    box.num = that.data.numbers
    list.push(box);
    params.record = JSON.stringify(list)
    params.buy_type = 1;
    util.showLoading("加载中");
    api.POST({
      params: params,
      url: app.globalData.base_url + 'order/submit',
      success: function (res) {
        util.hiddenLoading();
        if (util.isEmpty(res.data.code)) {
          wx.removeStorageSync('shopId')
          that.wxPayOrder(res.data.data.result.oid, res.data.data.result.type);
        } else if (res.data.code == "2499") {
          util.showError("库存不足");
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");
      }
    })
  },
  //支付接口
  wxPayOrder: function (oid, types) {
    var params = new Object()
    var that = this;
    params.oid = oid;
    api.POST({
      params: { oid: oid },
      url: app.globalData.base_url + 'payment/getWechatInfo',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          var preData = res.data.data.payinfo;
          wx.requestPayment({
            timeStamp: preData.timeStamp,
            nonceStr: preData.nonceStr,
            package: preData.package,
            signType: preData.signType,
            paySign: preData.paySign,
            success: function (res) {
              that.wineList(); //获取酒柜列表
              that.closeBuy();
            },
            fail: function (error) {
              util.showError("支付失败");
              wx.removeStorageSync('orderData');
            }
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");
      }
    })
  },
  //小店足迹按钮
  footprint: function () {
    wx.navigateTo({
      url: '/index/pages/storeFootprint/storeFootprint'
    })
  },
  //配送按钮
  peisong: function (e) {
    wx.navigateTo({
      url: '/wine/pages/wineDistribution/wineDistribution'
    })
  },
  //取货按钮
  pickUp: function (e) {
    wx.navigateTo({
      url: '/wine/pages/wineSelfGet/wineSelfGet'
    })
  },
  //商家二维码取货
  codePickUp: function () {
    wx.navigateTo({
      url: '/wine/pages/wineSelfGet/wineSelfGet'
    })
  },
  begWine:function(){
    wx.navigateTo({
      url: '/play/pages/beg/beg'
    })
  },
  //赠送按钮
  giving: function (e) {
    wx.navigateTo({
      url: '/wine/pages/giving/giving?sku_code=' + this.data.goodsInfo.sku_code
    })
  },
  //拆分数组
  split_array: function (arr, len, types) {
    var a_len = arr.length;
    var box_arr = [];
    var new_arr = [];
    var num =0;
    for (var i = 0; i < a_len; i ++) {
      if (types == "winBox") {
        if (arr[i].id) {
          num++;
        }
      }
    }
    for (var i = 0; i < a_len; i += len) {
      box_arr.push(arr.slice(i, i + len));
    }
    if (box_arr.length < 4) {
      var arr_new = [];
      for (var n = box_arr.length; n < 4; n++) {
        box_arr.push(arr_new);
      }
    }
    if (types=="winBox"){

      if (num > 0) {
        this.setData({
          codeCol: true
        })
      } else {
        this.setData({
          codeCol: false
        })
      }

      this.setData({
        newProductData: box_arr
      })
    } else if (types = "hops"){
      this.setData({
        newHopsData: box_arr
      })
    }
  },
  //  合成酒花
  marrying:function(){
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否"合成"该酒花',
      success: function (res) {
        if (res.confirm) {
          var id = that.data.goodsInfoHops.id;
          var sku_code = that.data.goodsInfoHops.sku_code;
          api.POST({
            params: { id: id },
            url: app.globalData.base_url + 'hops/synthesis',
            success: function (res) {
              if (util.isEmpty(res.data.code)) {
                that.flyOutHops();
                that.fadeInMarry();
                that.setData({
                  marry_code: sku_code,
                  marryImg: res.data.data.result.img,
                  marryName: res.data.data.result.ganme,
                  page: 1
                })
                that.wineList();
                that.hopsList();
              } else {
                util.showError(res.data.message);
              }
            },
            fail: function (fail) {
              util.showError("网络错误，请检查网络");
            }
          })
        }
      }
    })
  },

  // 分享事件
  onShareAppMessage: function (res) {
    var that = this;
    var linkCode = this.data.linkCode;
    var name = that.data.goodsInfoHops.hops_name
    var userinfo = app.globalData.accountInfo;
    var uid = userinfo.uid;
    var img = that.data.goodsInfoHops.share_img;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      return {
        title: '好友"' + userinfo.nickname + '"送您"' + name + '"酒花',
        path: '/pages/giftShare/giftShare?uid=' + uid + '&show_type=4&linkCode=' + linkCode+'&shareType=1',
        imageUrl: img,
        success: function (res) {
          that.sharehops();
        },
        fail: function (res) {
          // 转发失败
        }
      }
    }
  },
// 酒花分享回调
  sharehops:function(){
    var that = this;
    var linkCode = this.data.linkCode;
    api.POST({
      params: { linkCode: linkCode },
      url: app.globalData.base_url + 'hops/successSmg',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.outSelectHops();
          that.setData({
            page: 1
          })
          that.wineList();
          that.hopsList();
          // setTimeout(function(){
          //   util.showError("分享成功");
          // },500)
        } else {
          that.outSelectHops();
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");
      }
    })
  },

  //关注组件加载成功
  focusSuccessful:function(){
   //  console.log("chengg")
    this.setData({
      focusSuccessful:true
    })
  },

    //关注组件加载失败
  focusError:function(e){
   //  console.log("失败")
    this.setData({
      focusSuccessful: false
    })
  },

  //打开关注公众号引导
  focusUs:function(){
    // console.log(1);
    var focusSuccessful = this.data.focusSuccessful
    // console.log(focusComponent);
    if (focusSuccessful){
      this.setData({
        focusComponent: true
      })
      this.getHeightInfo();
    }else{
      this.setData({
        guideFocus: false
      })
    }
    
  },
    //关闭关注公众号引导
  guideFocusPage:function(){
    this.setData({
      guideFocus: true
    })
  },

  closeFocus:function(){
    if (this.data.focusComponent){
      //重新检查是否关注
      this.subscribe(); 
    }
    this.setData({
      focusComponent: false
    })

  },

  //获取个人状态详情
  userStatus: function (e) {
    var that = this;
    api.POST({
      params: "",
      url: app.globalData.base_url + 'user/status',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.setData({
             wine_cabinet_status: res.data.data.wine_cabinet_status
          })
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");
      }
    })
  },
   outward: util.debounce(function(){
      const that = this;
      let wine_cabinet_status = this.data.wine_cabinet_status;
      let text = '';
      if (wine_cabinet_status==1){
         text = '是否确认“隐藏”我的酒柜，确认后，好友将不能查看您酒柜中的商品，并不可以向您讨美酒'
      }else{
         text = '是否确认“公开”我的酒柜，公开 后，好友将能查看您酒柜中的商品，并可以向您讨美酒'
      }
      if (wine_cabinet_status==1){
         wine_cabinet_status =2
      }else{
         wine_cabinet_status =1
      }

      wx.showModal({
         title: '提示',
         content: text,
         success: function (res) {
            if (res.confirm) {
               api.POST({
                  params: { status: wine_cabinet_status},
                  url: app.globalData.base_url + 'Winecabinet/changeStatus',
                  success: function (res) {
                     if (util.isEmpty(res.data.code)) {
                        that.userStatus();
                     } else {
                        util.showError(res.data.message);
                     }
                  },
                  fail: function (fail) {
                     util.showError("请检查网络");
                  }
               })
            }
         }
      })


   }),


  //查看订单礼品弹框
  order_gift:function(){
    this.setData({
      show_order_gift:true
    })
  },

  //订单礼品弹框关闭
  order_gift_close:function(){
    this.setData({
      show_order_gift:false
    })
  },

  //我的订单
  myOrder:function(){
    wx.navigateTo({
      url: '/center/pages/myOrder/myOrder?types=2',
    })
  },

  //我的礼品卡
  myGift:function(){
    wx.navigateTo({
      url: '/play/pages/myGift/myGift',
    })
  },
   //前往我的订单
   deliveryOrder: function () {
      wx.navigateTo({
         url: '/center/pages/myOrder/myOrder?types=1',
      })
   },


  //空事件
  empty:function(){

  },
})